package com.manage.func.booksmanagement.childrenbooks.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.manage.base.bean.CommonResultBean;
import com.manage.base.controller.BaseController;
import com.manage.config.model.Config;
import com.manage.func.booksmanagement.childrenbooks.model.ChildrenBooksBean;
import com.manage.func.booksmanagement.childrenbooks.service.IChildrenBooksService;
import com.manage.user.model.User;
import com.manage.util.StringUtil;
import com.manage.util.SystemUtil;

/**
 * 少儿图书
 * 
 * @author xy
 *
 */
@Controller
@RequestMapping("/childrenbooks")
public class ChildrenBooksController extends BaseController {

	private static final long serialVersionUID = 1L;
	private static String DEFAULT_PREVFIX = "thumb_";
	private static Boolean DEFAULT_FORCE = false;

	static final Logger LOG = LoggerFactory.getLogger(ChildrenBooksController.class);

	@Autowired
	private IChildrenBooksService childrenbooksService;

	// 查询少儿图书
	@RequestMapping(value = "select", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean select(@RequestParam("data") String data) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("childrenbooks select called: " + data);
			ChildrenBooksBean bean = fromJson(data, ChildrenBooksBean.class);
			if (bean != null) {
				List<ChildrenBooksBean> beans = childrenbooksService.selectChildrenBooksList(bean);
				int size = childrenbooksService.selectTotalCount(bean);
				convertHttp(beans);
				sys.put("childrenbooks", beans);
				sys.put("size", size);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	private void convertHttp(List<ChildrenBooksBean> beans) {
		String context = SystemUtil.getAppProp("image_context");
		for (ChildrenBooksBean bean : beans) {
			if (StringUtil.notEmpty(bean.bookImageUrl)) {
				bean.bookImageUrl = "http://" + context + bean.bookImageUrl;
			}
			if (StringUtil.notEmpty(bean.thumbnailUrl)) {
				bean.thumbnailUrl = "http://" + context + bean.thumbnailUrl;
			}
		}
	}

	// 添加图书
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean add(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("childrenbooks add called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ChildrenBooksBean bean = fromJson(data, ChildrenBooksBean.class);

			bean = convertImagePath(bean);
			if (bean != null) {
				childrenbooksService.insertChildrenBooks(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	/**
	 * 图片上传
	 * 
	 * @param uploadFile
	 * @param data
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/image/upload")
	@ResponseBody
	public CommonResultBean pictureUpload(
			@RequestParam(value = "uploadFile", required = false) MultipartFile uploadFile,
			HttpServletRequest request) {
		if (uploadFile == null || uploadFile.getOriginalFilename().trim().equals("")) {
			CommonResultBean commonResultBean = new CommonResultBean();
			commonResultBean.setResult_code(Config.FAILE);
			commonResultBean.setResult_message("图片为空，上传失败");
			return commonResultBean;
		} else {
			try {
				String rootPath = super.getWebRootPath(request);
				String rootUrl = super.getWebRootUrl(request);
				// 保存大图
				String fileName = saveImage(uploadFile, rootPath, rootUrl);
				String fileFullName = Config.HTTP_TITLE + SystemUtil.getAppProp("image_context")
						+ Config.CHILDRENBOOKS_IMAGE_HTTP + fileName;
				// 生成缩略图
				String thumbnailPath = rootPath + Config.CHILDRENBOOKS_IMAGE_PATH + fileName;
				thumbnailImage(thumbnailPath, 100, 150);
				String thumbnailFileFullName = Config.HTTP_TITLE + SystemUtil.getAppProp("image_context")
						+ Config.CHILDRENBOOKS_IMAGE_HTTP + DEFAULT_PREVFIX + fileName;
				CommonResultBean commonResultBean = new CommonResultBean();
				commonResultBean.setResult_code(Config.SUCCESS);
				commonResultBean.setResult_message("主图片上传成功");
				Map<String, Object> result_map = new HashMap<String, Object>();
				result_map.put("url", fileFullName);
				result_map.put("thumbnailurl", thumbnailFileFullName);
				commonResultBean.setResult_map(result_map);
				return commonResultBean;

			} catch (Exception e) {
				e.printStackTrace();
				CommonResultBean commonResultBean = new CommonResultBean();
				commonResultBean.setResult_code(Config.FAILE);
				commonResultBean.setResult_message("主图片上传异常");
				return commonResultBean;
			}

		}
	}

	private String saveImage(MultipartFile uploadFile, String rootPath, String rootUrl) {
		try {
			// String httpUrl =
			// Config.HTTP_TITLE+SystemUtil.getAppProp("image_context");
			String suffix = uploadFile.getOriginalFilename()
					.substring(uploadFile.getOriginalFilename().lastIndexOf("."));
			String prePath = rootPath + Config.CHILDRENBOOKS_IMAGE_PATH;
			String filePath = System.currentTimeMillis() + getFixLenthString(6) + suffix;
			// String returnPath = httpUrl +Config.CHILDRENBOOKS_IMAGE_HTTP
			// +filePath;
			String savePath = prePath + filePath;
			File preDir = new File(prePath);
			if (!preDir.exists()) {
				preDir.mkdirs();
			}
			uploadFile.transferTo(new File(savePath));
			return filePath;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return null;
	}

	private static String getFixLenthString(int strLength) {

		Random rm = new Random();
		// 获得随机数
		double pross = (1 + rm.nextDouble()) * Math.pow(10, strLength);
		// 将获得的获得随机数转化为字符串
		String fixLenthString = String.valueOf(pross);
		// 返回固定的长度的随机数
		return fixLenthString.substring(1, strLength + 1);
	}

	// 更新图书
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean update(@RequestParam("data") String data, HttpServletRequest request) {
		CommonResultBean sys = new CommonResultBean();
		try {
			LOG.info("childrenbooks update called: " + data);
			User sysuser = (User) request.getSession().getAttribute(Config.USER_SESSION);
			if (null == sysuser) {
				sys.setErrorMsg("请先登录再进行操作");
				return sys;
			}
			ChildrenBooksBean bean = fromJson(data, ChildrenBooksBean.class);

			bean = convertImagePath(bean);
			if (bean != null) {
				childrenbooksService.updateChildrenBooks(bean);
				sys.setResult_code(Config.SUCCESS);
				sys.setResult_message(Config.SUCCESS_MSG);
				return sys;
			}
			sys.setErrorMsg("请求参数为空");
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	private ChildrenBooksBean convertImagePath(ChildrenBooksBean param) {
		try {
			if (StringUtil.notEmpty(param.bookImageUrl)) {
				String str = param.bookImageUrl.split(Config.CHILDRENBOOKS_IMAGE_HTTP)[1];
				param.bookImageUrl = Config.CHILDRENBOOKS_IMAGE_HTTP + str;
			}
			if (StringUtil.notEmpty(param.thumbnailUrl)) {
				String str = param.thumbnailUrl.split(Config.CHILDRENBOOKS_IMAGE_HTTP)[1];
				param.thumbnailUrl = Config.CHILDRENBOOKS_IMAGE_HTTP + str;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
		}
		return param;
	}

	// 删除图书
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public CommonResultBean delete(@RequestParam("data") String data) {
		LOG.info("ChildrenBooks delete: " + data);
		CommonResultBean sys = new CommonResultBean();
		try {
			ChildrenBooksBean bean = fromJson(data, ChildrenBooksBean.class);
			// int i =
			childrenbooksService.deleteChildrenBooks(bean);
			sys.setResult_code(Config.SUCCESS);
			sys.setResult_message(Config.SUCCESS_MSG);
			return sys;
		} catch (Exception e) {
			LOG.error(e.getMessage(), e);
			sys.setError();
		}
		return sys;
	}

	/**
	 * <p>
	 * Title: thumbnailImage
	 * </p>
	 * <p>
	 * Description: 根据图片路径生成缩略图
	 * </p>
	 * 
	 * @param imagePath
	 *            原图片路径
	 * @param w
	 *            缩略图宽
	 * @param h
	 *            缩略图高
	 * @param prevfix
	 *            生成缩略图的前缀
	 * @param force
	 *            是否强制按照宽高生成缩略图(如果为false，则生成最佳比例缩略图)
	 */
	public void thumbnailImage(File imgFile, int w, int h, String prevfix, boolean force) {
		LOG.info("childrenbooks thumbnailImage called");
		if (imgFile.exists()) {
			try {
				// ImageIO 支持的图片类型 : [BMP, bmp, jpg, JPG, wbmp, jpeg, png, PNG,
				// JPEG, WBMP, GIF, gif]
				String types = Arrays.toString(ImageIO.getReaderFormatNames());
				String suffix = null;
				// 获取图片后缀
				if (imgFile.getName().indexOf(".") > -1) {
					suffix = imgFile.getName().substring(imgFile.getName().lastIndexOf(".") + 1);
				} // 类型和图片后缀全部小写，然后判断后缀是否合法
				if (suffix == null || types.toLowerCase().indexOf(suffix.toLowerCase()) < 0) {
					return;
				}
				Image img = ImageIO.read(imgFile);
				if (!force) {
					// 根据原图与要求的缩略图比例，找到最合适的缩略图比例
					int width = img.getWidth(null);
					int height = img.getHeight(null);
					if ((width * 1.0) / w < (height * 1.0) / h) {
						if (width > w) {
							h = Integer.parseInt(new java.text.DecimalFormat("0").format(height * w / (width * 1.0)));
						}
					} else {
						if (height > h) {
							w = Integer.parseInt(new java.text.DecimalFormat("0").format(width * h / (height * 1.0)));
						}
					}
				}
				BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
				Graphics g = bi.getGraphics();
				g.drawImage(img, 0, 0, w, h, Color.LIGHT_GRAY, null);
				g.dispose();
				String p = imgFile.getPath();
				// 将图片保存在原目录并加上前缀
				ImageIO.write(bi, suffix, new File(
						p.substring(0, p.lastIndexOf(File.separator)) + File.separator + prevfix + imgFile.getName()));
			} catch (IOException e) {
				LOG.error(e.getMessage(), e);
			}
		} else {
			LOG.info("the image is not exist.");
		}
	}

	public void thumbnailImage(String imagePath, int w, int h, String prevfix, boolean force) {
		File imgFile = new File(imagePath);
		thumbnailImage(imgFile, w, h, prevfix, force);
	}

	public void thumbnailImage(String imagePath, int w, int h, boolean force) {
		thumbnailImage(imagePath, w, h, DEFAULT_PREVFIX, force);
	}

	public void thumbnailImage(String imagePath, int w, int h) {
		thumbnailImage(imagePath, w, h, DEFAULT_FORCE);
	}
}
